Ones and zeroes¶
Time: O(SxMxN); Space: O(MxN); medium
Given an array, strs, with strings consisting of only 0s and 1s. Also two integers m and n.
Now your task is to find the maximum number of strings that you can form with given m 0s and n 1s.
Each 0 and 1 can be used at most once.
Example 1:
Input: strs = [“10”,“0001”,“111001”,“1”,“0”], m = 5, n = 3
Output: 4
Explanation:
This are totally 4 strings can be formed by the using of 5 0s and 3 1s, which are “10”,“0001”,“1”,“0”.
Example 2:
Input: strs = [“10”,“0”,“1”], m = 1, n = 1
Output: 2
Explanation:
You could form “10”, but then you’d have nothing left. Better form “0” and “1”.
Constraints:
1 <= len(strs) <= 600
1 <= len(strs[i]) <= 100
strs[i] consists only of digits ‘0’ and ‘1’.
1 <= m, n <= 100
[1]:
class Solution1(object):
"""
Time: O(S*M*N), S is the size of the array
Space: O(M*N)
"""
def findMaxForm(self, strs, m, n):
"""
:type strs: List[str]
:type m: int
:type n: int
:rtype: int
"""
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for s in strs:
zero_count, one_count = 0, 0
for c in s:
if c == '0':
zero_count += 1
elif c == '1':
one_count += 1
for i in reversed(range(zero_count, m + 1)):
for j in reversed(range(one_count, n + 1)):
dp[i][j] = max(dp[i][j], dp[i-zero_count][j-one_count]+1)
return dp[m][n]
[2]:
s = Solution1()
strs = ["10","0001","111001","1","0"]
m = 5
n = 3
assert s.findMaxForm(strs, m, n) == 4
strs = ["10","0","1"]
m = 1
n = 1
assert s.findMaxForm(strs, m, n) == 2